<template>
  <div class="no-fly-zones-container">
    <div class="page-header">
      <h2>禁飞区管理</h2>
      <el-button type="primary" @click="handleAddNoFlyZone" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加禁飞区
      </el-button>
    </div>

    <!-- 搜索 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="禁飞区名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入禁飞区名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 禁飞区表格 -->
    <el-card class="no-fly-zones-table-card" shadow="hover">
      <el-table
        :data="noFlyZonesData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="name" label="禁飞区名称" width="180">
          <template #default="{ row }">
            <el-tag size="default" type="primary" effect="light">{{
              row.name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="zone_type" label="区域类型" width="120">
          <template #default="{ row }">
            <el-tag
              size="small"
              :type="row.zone_type === 'circle' ? 'success' : 'warning'"
              >{{ row.zone_type === "circle" ? "圆形" : "多边形" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="300" />
        <el-table-column label="高度范围" width="180">
          <template #default="{ row }">
            {{ row.min_altitude }}m - {{ row.max_altitude }}m
          </template>
        </el-table-column>
        <el-table-column label="时间范围" width="250">
          <template #default="{ row }">
            <div v-if="row.start_time && row.end_time">
              {{ formatDate(row.start_time) }}<br />
              至<br />
              {{ formatDate(row.end_time) }}
            </div>
            <div v-else>长期有效</div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              @click="handleEditNoFlyZone(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteNoFlyZone(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑禁飞区对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加禁飞区' : '编辑禁飞区'"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="noFlyZoneForm"
        :rules="noFlyZoneRules"
        ref="noFlyZoneFormRef"
        label-width="120px"
        class="no-fly-zone-form"
      >
        <el-form-item label="禁飞区名称" prop="name">
          <el-input
            v-model="noFlyZoneForm.name"
            placeholder="请输入禁飞区名称"
          />
        </el-form-item>

        <el-form-item label="区域类型" prop="zone_type">
          <el-radio-group
            v-model="noFlyZoneForm.zone_type"
            @change="onZoneTypeChange"
          >
            <el-radio label="circle">圆形</el-radio>
            <el-radio label="polygon">多边形</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 圆形区域属性 -->
        <div v-if="noFlyZoneForm.zone_type === 'circle'">
          <el-form-item label="中心纬度" prop="center_latitude">
            <el-input
              v-model.number="noFlyZoneForm.center_latitude"
              placeholder="请输入中心纬度"
            />
          </el-form-item>

          <el-form-item label="中心经度" prop="center_longitude">
            <el-input
              v-model.number="noFlyZoneForm.center_longitude"
              placeholder="请输入中心经度"
            />
          </el-form-item>

          <el-form-item label="半径(米)" prop="radius">
            <el-input
              v-model.number="noFlyZoneForm.radius"
              placeholder="请输入半径(米)"
            />
          </el-form-item>
        </div>

        <!-- 多边形区域属性 -->
        <div v-else-if="noFlyZoneForm.zone_type === 'polygon'">
          <el-form-item label="坐标点" prop="coordinates">
            <div
              v-if="
                noFlyZoneForm.coordinates &&
                noFlyZoneForm.coordinates.length > 0
              "
            >
              <div
                v-for="(coord, index) in noFlyZoneForm.coordinates"
                :key="index"
                class="coordinate-item"
              >
                <el-input
                  v-model.number="coord.lat"
                  placeholder="纬度"
                  style="width: 100px; margin-right: 10px"
                />
                <el-input
                  v-model.number="coord.lng"
                  placeholder="经度"
                  style="width: 100px; margin-right: 10px"
                />
                <el-button
                  type="danger"
                  size="small"
                  @click="removeCoordinate(index)"
                  v-if="index > 0"
                >
                  删除
                </el-button>
              </div>
              <el-button type="primary" size="small" @click="addCoordinate">
                添加坐标点
              </el-button>
            </div>
            <div v-else>
              <el-button type="primary" size="small" @click="addCoordinate">
                添加第一个坐标点
              </el-button>
            </div>
          </el-form-item>
        </div>

        <el-form-item label="最小高度(米)" prop="min_altitude">
          <el-input
            v-model.number="noFlyZoneForm.min_altitude"
            placeholder="请输入最小高度(米)"
          />
        </el-form-item>

        <el-form-item label="最大高度(米)" prop="max_altitude">
          <el-input
            v-model.number="noFlyZoneForm.max_altitude"
            placeholder="请输入最大高度(米)"
          />
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="noFlyZoneForm.start_time"
            type="datetime"
            placeholder="请选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="noFlyZoneForm.end_time"
            type="datetime"
            placeholder="请选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled="!noFlyZoneForm.start_time"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="noFlyZoneForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入禁飞区描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { noFlyZoneService } from "@/api/modules/noFlyZone";

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN");
};

export default {
  name: "NoFlyZones",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const noFlyZoneFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      name: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 禁飞区表单
    const noFlyZoneForm = reactive({
      id: "",
      name: "",
      zone_type: "circle", // 'circle' or 'polygon'
      center_latitude: 0,
      center_longitude: 0,
      radius: 1000,
      coordinates: [],
      min_altitude: 0,
      max_altitude: 1000,
      start_time: "",
      end_time: "",
      description: "",
    });

    // 表单验证规则
    const noFlyZoneRules = {
      name: [{ required: true, message: "请输入禁飞区名称", trigger: "blur" }],
      zone_type: [
        { required: true, message: "请选择区域类型", trigger: "change" },
      ],
      center_latitude: [
        {
          required: noFlyZoneForm.zone_type === "circle",
          message: "请输入中心纬度",
          trigger: "blur",
        },
        {
          type: "number",
          min: -90,
          max: 90,
          message: "纬度必须在-90到90之间",
          trigger: "blur",
        },
      ],
      center_longitude: [
        {
          required: noFlyZoneForm.zone_type === "circle",
          message: "请输入中心经度",
          trigger: "blur",
        },
        {
          type: "number",
          min: -180,
          max: 180,
          message: "经度必须在-180到180之间",
          trigger: "blur",
        },
      ],
      radius: [
        {
          required: noFlyZoneForm.zone_type === "circle",
          message: "请输入半径",
          trigger: "blur",
        },
        { type: "number", min: 1, message: "半径必须大于0", trigger: "blur" },
      ],
      coordinates: [
        {
          required: noFlyZoneForm.zone_type === "polygon",
          message: "请添加坐标点",
          trigger: "change",
          validator: (rule, value, callback) => {
            if (
              noFlyZoneForm.zone_type === "polygon" &&
              (!value || value.length < 3)
            ) {
              callback(new Error("多边形必须至少包含3个坐标点"));
            } else {
              callback();
            }
          },
        },
      ],
      min_altitude: [
        { required: true, message: "请输入最小高度", trigger: "blur" },
        {
          type: "number",
          min: 0,
          message: "最小高度必须大于等于0",
          trigger: "blur",
        },
      ],
      max_altitude: [
        { required: true, message: "请输入最大高度", trigger: "blur" },
        {
          type: "number",
          min: 1,
          message: "最大高度必须大于0",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (value <= noFlyZoneForm.min_altitude) {
              callback(new Error("最大高度必须大于最小高度"));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
    };

    // 监听区域类型变化，动态调整验证规则
    watch(
      () => noFlyZoneForm.zone_type,
      (newType, oldType) => {
        // 当从圆形切换到多边形时，清空圆形相关数据
        if (oldType === "circle" && newType === "polygon") {
          noFlyZoneForm.center_latitude = 0;
          noFlyZoneForm.center_longitude = 0;
          noFlyZoneForm.radius = 1000;
          noFlyZoneForm.coordinates = [];
        }
        // 当从多边形切换到圆形时，清空多边形相关数据
        else if (oldType === "polygon" && newType === "circle") {
          noFlyZoneForm.coordinates = [];
        }
      }
    );

    // 禁飞区数据
    const noFlyZonesData = ref([]);

    // 初始化
    onMounted(() => {
      fetchNoFlyZones();
    });

    // 获取禁飞区列表
    const fetchNoFlyZones = async () => {
      loading.value = true;
      try {
        // 从后端API获取禁飞区数据
        const response = await noFlyZoneService.getNoFlyZones({
          page: pagination.currentPage,
          page_size: pagination.pageSize,
          name: searchForm.name || undefined,
        });

        if (response.code === 200) {
          noFlyZonesData.value = response.data.items;
          pagination.total = response.data.total;
        } else {
          ElMessage.error(response.message || "获取禁飞区列表失败");
        }

        loading.value = false;
      } catch (error) {
        console.error("获取禁飞区列表失败:", error);
        ElMessage.error(error.response?.data?.message || "获取禁飞区列表失败");
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchNoFlyZones();
    };

    // 重置
    const resetSearch = () => {
      searchForm.name = "";
      pagination.currentPage = 1;
      fetchNoFlyZones();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchNoFlyZones();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchNoFlyZones();
    };

    // 打开添加禁飞区对话框
    const handleAddNoFlyZone = () => {
      dialogType.value = "add";
      resetNoFlyZoneForm();
      dialogVisible.value = true;
    };

    // 打开编辑禁飞区对话框
    const handleEditNoFlyZone = (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;

      // 复制基础数据
      Object.assign(noFlyZoneForm, {
        id: row.id,
        name: row.name || "",
        zone_type: row.zone_type || "circle",
        // 确保数值类型正确转换，避免字符串转数值的问题
        center_latitude: row.center_latitude !== undefined ? Number(row.center_latitude) : 0,
        center_longitude: row.center_longitude !== undefined ? Number(row.center_longitude) : 0,
        radius: row.radius !== undefined ? Number(row.radius) : 1000,
        min_altitude: Number(row.min_altitude) || 0,
        max_altitude: Number(row.max_altitude) || 1000,
        start_time: row.start_time || "",
        end_time: row.end_time || "",
        description: row.description || "",
        coordinates: [] // 初始化为空数组
      });

      // 处理多边形坐标格式转换
      if (row.zone_type === "polygon") {
        // 检查数据格式，如果是后端格式[[lng, lat], ...]，则转换为前端表单格式[{lat, lng}, ...]
        if (Array.isArray(row.polygon_points)) {
          noFlyZoneForm.coordinates = row.polygon_points.map(point => ({
            lat: Number(point[1]),  // 确保转换为数值类型
            lng: Number(point[0])   // 确保转换为数值类型
          }));
        } else if (Array.isArray(row.coordinates)) {
          // 如果是前端格式[{lat, lng}, ...]，则直接使用并确保数值类型
          noFlyZoneForm.coordinates = row.coordinates.map(point => ({
            lat: Number(point.lat),
            lng: Number(point.lng)
          }));
        }
      } else if (row.zone_type === "circle") {
        // 确保圆形区域数据的正确处理，检查是否存在其他可能的数据结构
        // 检查是否存在lat/lng属性（地图控件可能使用的格式）
        if (row.lat !== undefined && row.lng !== undefined) {
          noFlyZoneForm.center_latitude = Number(row.lat);
          noFlyZoneForm.center_longitude = Number(row.lng);
        }
        // 检查是否存在其他可能的中心点表示方式
        if (row.center && typeof row.center === 'object') {
          if (row.center.lat !== undefined && row.center.lng !== undefined) {
            noFlyZoneForm.center_latitude = Number(row.center.lat);
            noFlyZoneForm.center_longitude = Number(row.center.lng);
          } else if (row.center[0] !== undefined && row.center[1] !== undefined) {
            noFlyZoneForm.center_longitude = Number(row.center[0]); // 假设格式为 [lng, lat]
            noFlyZoneForm.center_latitude = Number(row.center[1]);
          }
        }
      }

      dialogVisible.value = true;
    };

    // 删除禁飞区
    const handleDeleteNoFlyZone = (row) => {
      ElMessageBox.confirm(`确定要删除禁飞区「${row.name}」吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            const response = await noFlyZoneService.deleteNoFlyZone(row.id);

            if (response.code === 200) {
              ElMessage.success("删除成功");
              fetchNoFlyZones();
            } else {
              ElMessage.error(response.message || "删除禁飞区失败");
            }
          } catch (error) {
            console.error("删除禁飞区失败:", error);
            ElMessage.error(error.response?.data?.message || "删除禁飞区失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
        });
    };

    // 重置禁飞区表单
    const resetNoFlyZoneForm = () => {
      if (noFlyZoneFormRef.value) {
        noFlyZoneFormRef.value.resetFields();
      }
      Object.assign(noFlyZoneForm, {
        id: "",
        name: "",
        zone_type: "circle",
        center_latitude: 0,
        center_longitude: 0,
        radius: 1000,
        coordinates: [],
        min_altitude: 0,
        max_altitude: 1000,
        start_time: "",
        end_time: "",
        description: "",
      });
    };

    // 区域类型变化处理
    const onZoneTypeChange = () => {
      // 清空验证错误提示
      if (noFlyZoneFormRef.value) {
        noFlyZoneFormRef.value.clearValidate();
      }
    };

    // 添加坐标点
    const addCoordinate = () => {
      noFlyZoneForm.coordinates.push({ lat: 0, lng: 0 });
    };

    // 删除坐标点
    const removeCoordinate = (index) => {
      noFlyZoneForm.coordinates.splice(index, 1);
    };

    // 提交表单
    const handleSubmit = () => {
      noFlyZoneFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            // 准备提交数据
            const submitData = {
              name: noFlyZoneForm.name.trim(),
              zone_type: noFlyZoneForm.zone_type,
              // 确保所有数值类型正确转换
              min_altitude: Number(noFlyZoneForm.min_altitude),
              max_altitude: Number(noFlyZoneForm.max_altitude),
              description: noFlyZoneForm.description || "",
            };

            // 根据区域类型添加对应的字段
            if (noFlyZoneForm.zone_type === "circle") {
              // 确保圆形区域数据为正确的数值类型，使用后端期望的字段名
              submitData.lat = Number(noFlyZoneForm.center_latitude);
              submitData.lng = Number(noFlyZoneForm.center_longitude);
              submitData.radius = Number(noFlyZoneForm.radius);
            } else {
              // 将前端格式[{lat, lng}, ...]转换为后端期望的格式[[lng, lat], ...]
              submitData.polygon_points = noFlyZoneForm.coordinates.map(point => [
                Number(point.lng),  // 确保数值类型正确
                Number(point.lat)   // 确保数值类型正确
              ]);
            }

            // 添加时间范围（如果有）
            if (noFlyZoneForm.start_time) {
              submitData.start_time = noFlyZoneForm.start_time;
            }
            if (noFlyZoneForm.end_time) {
              submitData.end_time = noFlyZoneForm.end_time;
            }

            if (dialogType.value === "add") {
              // 添加禁飞区
              const response = await noFlyZoneService.createNoFlyZone(
                submitData
              );

              if (response.code === 200) {
                ElMessage.success("添加成功");
              } else {
                ElMessage.error(response.message || "添加禁飞区失败");
                return;
              }
            } else {
              // 更新禁飞区
              const response = await noFlyZoneService.updateNoFlyZone(
                noFlyZoneForm.id,
                submitData
              );

              if (response.code === 200) {
                ElMessage.success("更新成功");
              } else {
                ElMessage.error(response.message || "更新禁飞区失败");
                return;
              }
            }

            dialogVisible.value = false;
            fetchNoFlyZones();
            editingId.value = null;
          } catch (error) {
            console.error("操作禁飞区失败:", error);
            ElMessage.error(error.response?.data?.message || "操作失败");
          } finally {
            dialogLoading.value = false;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      noFlyZoneFormRef,
      searchForm,
      pagination,
      noFlyZoneForm,
      noFlyZoneRules,
      noFlyZonesData,
      editingId,
      deletingId,
      formatDate,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddNoFlyZone,
      handleEditNoFlyZone,
      handleDeleteNoFlyZone,
      onZoneTypeChange,
      addCoordinate,
      removeCoordinate,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.no-fly-zones-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.no-fly-zones-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-fly-zone-form .el-form-item {
  margin-bottom: 20px;
}

.coordinate-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.coordinate-item .el-input {
  width: 120px;
  margin-right: 10px;
}
</style>
